package top.lanscarlos.ashcraft.controller;

import com.google.gson.JsonObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.controller
 *
 * @author Lanscarlos
 * @since 2022-05-25 22:50
 */
@RestController
@RequestMapping(value = "/upload")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UploadController {

    @RequestMapping(value = "/image")
    public Object uploadImage(
            JsonObject json,
            HttpServletRequest request,
            MultipartFile file
    ) {
        System.out.println(request.getServletContext().getRealPath("/images/"));
        try {
            String path = request.getServletContext().getRealPath("/images/");
            String name = UUID.randomUUID().toString().replace("-", "");
            System.out.println(path);
            File target = new File(path + name);
            if (!target.getParentFile().exists()) {
                target.getParentFile().mkdirs();
            }
            file.transferTo(target);
            json.addProperty("result", true);
        } catch (Exception e) {
            json.addProperty("result", false);
            e.printStackTrace();
        }
        return json;
    }

}
